package com.luojing.NIO;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @author luojing
 * @create 2018/12/03 9:32 AM
 **/
public class SocketChannelTest {

  public static void main(String[] args) throws IOException {
    SocketChannel socketChannel = SocketChannel.open();
    socketChannel.connect(new InetSocketAddress("127.0.0.1",8080));
    ByteBuffer buffer = ByteBuffer.allocate(10);
    socketChannel.read(buffer);
    byte[] data = buffer.array();
    String msg = new String(data).trim();
    System.out.println("client receive msg from server:" + msg);
    ByteBuffer outBuffer = ByteBuffer.wrap(msg.getBytes());
    socketChannel.write(outBuffer);
  }

}

class ServerSocketChannelTest{

  public static void main(String[] args) throws IOException {
    ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
    serverSocketChannel.socket().bind(new InetSocketAddress(8080));

    while (true) {
      // 一旦有一个 TCP 连接进来，就对应创建一个 SocketChannel 进行处理
      SocketChannel socketChannel = serverSocketChannel.accept();
      socketChannel.configureBlocking(false);
      socketChannel.write(ByteBuffer.wrap(new String("hello").getBytes()));


    }
  }
}